/**
 * 群组相关
 */
'use strict'

YX.fn.team = function () {
	this.$teamInfo = $('#teamInfo')
	this.$teamInfoContainer = $('#teamInfoContainer')

	//搜索群组列表
	this.$searcTeamCaseList = $('#searcTeamCaseList')
	this.$searchTeamAndCaseList = $('#searchTeamAndCaseList')
	this.$myCreate = $(".myCreate")
	this.$myJoin = $(".myJoin")
	this.$searchTeamAndCaseList.bind("input propertychange",this.searchTeamAndCaseList.bind(this))
	this.$searchTeamAndCaseList.blur(this.searchTeamAndCaseBlur.bind(this))
	this.$searchTeamAndCaseList.focus(this.searchTeamAndCaseFocus.bind(this))
	this.$searcTeamCaseList.delegate('.teamul .teamli','click',this.showTeamBox.bind(this))
	this.$myCreate.bind('click',this.myCreateClick.bind(this));
	this.$myJoin.bind('click',this.myJoinClick.bind(this));

	//搜索群面板
	this.$searchBox = $('#searchTeamBox')
	this.$searchBox.delegate('.j-close', 'click', this.hideTeamSearch.bind(this))
	this.$searchBox.delegate('.j-search', 'click', this.doTeamSearch.bind(this))
	this.$searchBox.delegate('.j-back', 'click', this.resetTeamSearch.bind(this))
	this.$searchBox.delegate('.j-chat', 'click', this.doTeamChat.bind(this))
	this.$searchBox.delegate('.j-add', 'click', this.doTeamAdd.bind(this))
	// 左侧面板群组中的三个按钮
	$('#createTeam').on('click', this.showTeamView.bind(this, 0, 0))
	// $('#createAdvanceTeam').on('click', this.showTeamView.bind(this, 0, 1))//事件移到案件中去
	$('#searchAdvanceTeam').on('click', this.showTeamSearch.bind(this, 0, 1))
	//群资料
	this.$teamInfo.on('click', this.showTeamInfo.bind(this))
	this.$teamInfoContainer.delegate('.j-backBtn', 'click', this.hideTeamInfo.bind(this))
	this.$teamInfoContainer.delegate('#teamMemberList .first', 'click', this.showTeamView.bind(this, 1))
	this.$teamInfoContainer.delegate('#teamMemberList .hover', 'click', this.removeTeamMember.bind(this))
	this.$teamInfoContainer.delegate('#teamName', 'click', this.editTeamInfo)
	this.$teamInfoContainer.delegate('#teamDesc', 'click', this.editTeamInfo)
	this.$teamInfoContainer.delegate('.j-exitTeam', 'click', this.exitTeam.bind(this))
	this.$teamInfoContainer.delegate('.j-dismissTeam', 'click', this.doDismissTeam.bind(this))
	// this.$teamInfoContainer.delegate('#teamNameInput', 'blur', this.saveTeamName.bind(this))
	this.$teamInfoContainer.delegate('#editButtonConfirm','click',this.saveTeamName.bind(this))
	this.$teamInfoContainer.delegate('#editButtonCancle','click',this.hideTeamEditInfo.bind(this))

	// this.$teamInfoContainer.delegate('#teamDescInput', 'blur', this.saveTeamDesc.bind(this))
	this.$teamInfoContainer.delegate('#editareaButtonConfirm','click',this.saveTeamDesc.bind(this))
	this.$teamInfoContainer.delegate('#editareaButtonCancle','click',this.hideTeamIntEditInfo.bind(this))

	this.$teamInfoContainer.delegate('.j-teamAvatar', 'click', this.showModifyAvatar.bind(this, "team"))
	this.$teamInfoContainer.delegate('.j-joinMode', 'change', this.setJoinMode.bind(this))
	this.$teamInfoContainer.delegate('.j-inviteMode', 'change', this.setInviteMode.bind(this))
	this.$teamInfoContainer.delegate('.j-beInviteMode', 'change', this.setBeInviteMode.bind(this))
	this.$teamInfoContainer.delegate('.j-updateTeamMode', 'change', this.setUpdateTeamMode.bind(this))

	//关联案件
	this.$relevanceCaseContainer = $('#relevanceCaseContainer');
	this.$teamInfoContainer.delegate('#caserelate','click',this.showRelevanceCase.bind(this))
	this.$relevanceCaseContainer.delegate('.jcase-backBtn', 'click', this.hiderelevanceCaseInfo.bind(this))
	this.relevanceCaseList = [];

}

/** 
 *监听搜索群组和案件列表的输入框
 *  
 */ 
YX.fn.searchTeamAndCaseList = function(){
	var $input = $('#searchTeamAndCaseList'),
		name = $input.val().trim(),
		that = this,
		searchList = new Array();
	var teamList = this.cache.getTeamlist();
	
	//根据输入框值判断是用teamId还是群组名称进行筛选
	if(!name){
		$('#searchTeamAndCaseList').val("")
		this.$searcTeamCaseList.html("");
		return;
	}
	if(checkNumber(name)){//数字
		for(var i = 0;i<teamList.length;i++){
			if(teamList[i].teamId.indexOf(name) != -1 && teamList[i].type == 'advanced'){
				searchList.push(teamList[i])
			}
		}
	}else{
		for(var i = 0;i<teamList.length;i++){
			if(teamList[i].name.indexOf(name) != -1 && teamList[i].type == 'advanced'){
				searchList.push(teamList[i])
			}
		}
	}
	this.setSearchTeamAndCaseNode(searchList);
}

YX.fn.searchTeamAndCaseFocus = function(){
	console.log("聚焦")
}

YX.fn.searchTeamAndCaseBlur = function(){
	var that = this;
	setTimeout(function(){
		// $('#searchTeamAndCaseList').val("")
		that.$searcTeamCaseList.html("");
	},500);
	
}

//显示html节点
YX.fn.setSearchTeamAndCaseNode = function(list){
	console.log("搜索出来的列表=",list)
	// var tmp1 = '<div class="panel_team"><div class="panel_team-title">讨论组</div><ul class="j-normalTeam">',
	var tmp2 = '<div class="searchteamTitle">群组</div><ul class="teamul">',
	flag1 = false,
	flag2 = false,
	html = '',
	info,
	teams = list;
	if (teams && teams.length > 0) {
		for (var i = 0, l = teams.length; i < l; ++i) {
			info = teams[i];
			// if (info.type === 'normal') {
			//     flag1 = true;
			//     tmp1 += ['<li class="panel_item '+(info.crtSession===info.target?'active':'')+'" data-gtype="normal" data-type="team" data-account="' + info.teamId + '">',
			//                 '<div class="panel_avatar"><img class="panel_image" src="'+info.avatar+'"/></div>',
			//                 '<div class="panel_text">',
			//                     '<p class="panel_single-row">'+info.nick+'</p>',
			//                 '</div>',
			//             '</li>'].join("");
			// } else 
			// if (info.type === 'advanced') {
				flag2 = true;
				tmp2 += ['<li class="teamli"  data-account='+info.teamId+'>',
							'<p class="teamname">'+info.name+'</p>',
							'<div class="teamInfo">',
									'<span>ID:</span><span>'+info.teamId+'</span><span>于'+transTimeFormatter(info.createTime)+'创建</span>',
							'</div>',
						'</li>'].join("");
			// }
		}
		// tmp1 += '</ul></div>';
		tmp2 += '</ul>';
		if (flag1 && flag2) {
			html = tmp2 + tmp1;
		} else if (flag1 && !flag2) {
			html = tmp1;
		} else if (!flag1 && flag2) {
			html = tmp2;
		} else {
			html = '<div class="searchNolist">找不到匹配的结果</div>';
		}
	} else {
		html = '<div class="searchNolist">找不到匹配的结果</div>';
	}
	// console.log("搜索出的案件列表=",html)
	this.$searcTeamCaseList.html(html);
}

//点击列表
YX.fn.showTeamBox = function(e){
	var account = e.currentTarget.getAttribute("data-account");
	this.openChatBox(account,'team');
}

YX.fn.myCreateClick = function(){
	$(".myCreate").addClass("slt")
	$(".myJoin").removeClass("slt")
	this.buildTeams()
}

YX.fn.myJoinClick = function(){
	$(".myCreate").removeClass("slt")
	$(".myJoin").addClass("slt")
	this.buildTeams()
}


/**
 * 最近联系人显示
 * @return {void}
 */
YX.fn.buildTeams = function (id) {
	console.log("群组列表=======",this.cache.getTeamlist())
	//此处将群组区分是我创建的还是我加入的
	var teamCacheList = this.cache.getTeamlist();
	var myAccId = sessionStorage.getItem('uid');
	var myCreateList = [],myJoinList = [];
	var teamList = [];
	if(teamCacheList.length > 0){
		for(var i=0;i<teamCacheList.length;i++){
			if(teamCacheList[i].owner == myAccId){
				myCreateList.push(teamCacheList[i]);
			}else{
				myJoinList.push(teamCacheList[i]);
			}
		}
	}
	if(this.$myCreate.hasClass("slt")){
		teamList = myCreateList;
	}else if(this.$myJoin.hasClass("slt")){
		teamList = myJoinList;
	}
	console.log("teamList===",teamList)

	var data = {
		teams: teamList
	}
	if (!this.teams) {
		var options = {
			data: data,
			infoprovider: this.infoProvider.bind(this),
			onclickavatar: this.clickTeamAvatar.bind(this),
			onclickitem: this.openChatBox.bind(this)
		}
		this.teams = new NIMUIKit.TeamList(options)
		this.teams.inject($('#teams').get(0))
	} else {
		this.teams.update(data)
	}
	this.doPoint()
}

/**
 * 主动去拿群列表
 */
YX.fn.getTeamMembers = function (id, callback) {
	if (!(callback instanceof Function)) {
		callback = function () {}
	}
 	var that = this
	this.mysdk.getTeamMembers(id, function (err, obj) {
		if (!err) {
			that.cache.setTeamMembers(id, obj)
			callback()
		} else {
			layer.msg(err.message,{icon:2})
		}
	})
}
/**
 * 点击群组列表头像
 * demo里跟点击列表处理一致了
 */
YX.fn.clickTeamAvatar = function (account, type) {
	$("#teams").find("li.active").removeClass("active")
	this.openChatBox(account, type)
}
/**
 * 联系人选择界面展示
 * @param  {int} type 0为新建群添加成员，1为在已有群的情况下添加成员
 * @param  {int} teamType 高级群1 普通群 0
 * @return {void}      
 */
YX.fn.showTeamView = function (type, teamType) {
	var that = this
	this.teamType = teamType
	var list = that.cache.getFriendslistOnShow()
	// console.log("好友列表=",list)
	if (type !== 0) {//添加成员
		var teamId = that.crtSessionAccount
		that.mysdk.getTeamMembers(
			teamId,
			function (error, obj) {
				//给已经在群的好友标记
				var members = error ? [] : obj.members
				console.log("群组成员===",members);
				//开启弹框 
				// that.dialog.open({ list: list, cbConfirm: that.createTeam, env: that, yx: that, selectedlist: members })
				that.dialog.openMember(members,that.departOpers,that.crtSessionAccount,that);
			}
		)
		//用来区分是否创群
		that.addTeamMemberTag = true
	} else {//新增群组
		//开启弹框
		// that.dialog.open({ list: list, cbConfirm: that.createTeam, env: that, yx: that })
		that.addTeamMemberTag = false
		//打开右侧创建创建群组界面
		// that.showCreateTeamInfo();
	}

}



/**
 * 
 * 
 */
/**
 * 回调：创建群
 * @param {object} list 已选中的人的列表
 */
YX.fn.createTeam = function (list) {
	// var accounts = [],
	// 	names = [],
	// 	teamId = this.addTeamMemberTag && this.crtSessionAccount,
	// 	that = this

	// for (var i in list) {
	// 	accounts.push(i)
	// 	names.push(list[i])
	// }
	// console.log("list===",list)

	// // 如果存在群id，则为新添加成员
	// if (!!teamId) {
	// 	this.mysdk.addTeamMembers({
	// 		teamId: teamId,
	// 		accounts: accounts,
	// 		ps: '',
	// 		done: function (error, params) {
	// 			if (error) { alert('添加成员失败') }
	// 		}
	// 	})
	// 	this.$teamInfoContainer.addClass('hide')
	// 	return;
	// }

	// // 创建普通群
	// var owner = this.cache.getUserById(userUID).nick
	// names = [owner].concat(names).join('、').slice(0, 20)
	// if (that.teamType === 0) {
	// 	this.mysdk.createTeam({
	// 		type: 'normal',
	// 		name: names + '等人',
	// 		accounts: accounts,
	// 		done: function (error, t) {
	// 			if (!error) {
	// 				that.cache.addTeam(t.team)
	// 				that.buildTeams()
	// 				$('#teamsWrap .j-normalTeam li[data-account="' + t.team.teamId + '"]').click()

	// 			} else {
	// 				alert("创建失败")
	// 			}
	// 		}
	// 	})
	// } else {
	// 	this.mysdk.createTeam({
	// 		type: 'advanced',
	// 		name: names + '等人',
	// 		accounts: accounts,
	// 		joinMode: 'needVerify',
	// 		done: function (error, t) {
	// 			if (!error) {
	// 				console.log("创建成功返回======",t)
	// 				that.cache.addTeam(t.team)
	// 				that.buildTeams()
	// 				$('#teamsWrap .j-advanceTeam li[data-account="' + t.team.teamId + '"]').click()

	// 			} else {
	// 				alert(error.message)
	// 			}
	// 		}
	// 	})
	// }

	// this.$teamInfoContainer.addClass('hide')
}
/***************************
 * 搜索高级群
 ***************************/
YX.fn.showTeamSearch = function () {
	this.searchData = null
	this.$searchBox.removeClass("hide")
	this.$mask.removeClass('hide')
	this.$searchBox.find(".j-account").focus()
}
YX.fn.hideTeamSearch = function () {
	this.resetTeamSearch()
	this.$searchBox.addClass("hide")
	this.$mask.addClass('hide')
}
YX.fn.doTeamSearch = function () {
	var account = $.trim(this.$searchBox.find(".j-account").val())
	if (/^\d+$/.test(account)) {
		this.mysdk.getTeam(account, this.cbDoTeamSearch.bind(this))
	} else {
		layer.msg("输入有误（群ID必须是数字）",{icon:2})
	}
}
YX.fn.cbDoTeamSearch = function (err, data) {
	if (err) {
		layer.msg(err.message,{icon:2})
	} else {
		if (data.type === "normal" || data.valid === false) {
			layer.msg("群不存在",{icon:2})
			return
		}
		var $info = this.$searchBox.find(".info")
		var teamId = data.teamId
		$info.find(".j-name").html(data.name)
		$info.find(".j-teamId").html(data.teamId)
		if (this.cache.hasTeam(teamId)) {
			this.$searchBox.addClass("inTeam")
		} else {
			this.$searchBox.addClass("notInTeam")
		}
	}
}
YX.fn.resetTeamSearch = function () {
	this.$searchBox.attr('class', "m-dialog")
	this.$searchBox.find(".j-account").val("")
}
YX.fn.doTeamChat = function () {
	var account = $.trim(this.$searchBox.find(".j-account").val())
	this.openChatBox(account, "team")
	this.hideTeamSearch()
}
YX.fn.doTeamAdd = function () {
	var account = $.trim(this.$searchBox.find(".j-account").val())
	this.mysdk.applyTeam(account)
}
/********************************************************************
 * 群资料
********************************************************************/
YX.fn.showTeamInfo = function () {
	var that = this
	this.$teamInfoContainer.load('./teamInfo.html', function () {
		// 获取群成员
		var teamId = that.crtSessionAccount,
			teamInfo = that.cache.getTeamById(teamId)
			console.log("群资料信息===",teamInfo)
		if (!teamInfo) {
			return
		}
		var type = teamInfo.type,
			teamName = teamInfo.name,
			teamOwner = teamInfo.owner,
			intro = teamInfo.intro || "",
			joinMode = teamInfo.joinMode || "",
			beInviteMode = teamInfo.beInviteMode || "",
			inviteMode = teamInfo.inviteMode || "",
			updateTeamMode = teamInfo.updateTeamMode || "",
			myTeamInfo,
			html = '',
			$userList = $('#teamMemberList'),
			// $teamId = that.$teamInfoContainer.find(".j-teamId"),
			// $teamAvatar = that.$teamInfoContainer.find(".j-teamAvatar"),
			$teamName = $('#teamName'),
			$teamDesc = $('#teamDesc'),
			$teramid = $('#teamid'),
			$createtime = $('#createtime');
		
			
		var members;

		//判断是否是当事人
		var applyUserAccid = "";
		if(teamInfo.serverCustom){
			applyUserAccid = JSON.parse(teamInfo.serverCustom).applyUserAccid;
		}

		// 高级群
		var showRole = function () {
			myTeamInfo = that.cache.getTeamMemberInfo(userUID, teamId)
			if (type === "advanced") {
				//其本信息
				that.$teamInfoContainer.removeClass("normal").find('.j-advanced').removeClass("hide")
				
				var avatarUrl = teamInfo.avatar ? (teamInfo.avatar + "?imageView&thumbnail=40y40") : "images/advanced.png"
				// $teamAvatar[0].src = avatarUrl
				if (myTeamInfo.type === "owner" || (myTeamInfo.type === "manager")) {
					// that.$teamInfoContainer.find('.j-joinMode[value=' + joinMode + ']').attr("checked", 'checked')
					// that.$teamInfoContainer.find('.j-beInviteMode[value=' + beInviteMode + ']').attr("checked", 'checked')
					// that.$teamInfoContainer.find('.j-inviteMode[value=' + inviteMode + ']').attr("checked", 'checked')
					// that.$teamInfoContainer.find('.j-updateTeamMode[value=' + updateTeamMode + ']').attr("checked", 'checked')
					$teamName.addClass('owner')
					$teamDesc.addClass('owner')
					// $teamAvatar.addClass('active')
					that.$teamInfoContainer.find('.editpen').removeClass('hide')
				} else {
					that.$teamInfoContainer.find('.editpen').addClass('hide')
					// that.$teamInfoContainer.find('.j-joinMode').attr("disabled", 'disabled').filter('[value=' + joinMode + ']').attr("checked", 'checked')
					// that.$teamInfoContainer.find('.j-beInviteMode').attr("disabled", 'disabled').filter('[value=' + beInviteMode + ']').attr("checked", 'checked')
					// that.$teamInfoContainer.find('.j-inviteMode').attr("disabled", 'disabled').filter('[value=' + inviteMode + ']').attr("checked", 'checked')
					// that.$teamInfoContainer.find('.j-updateTeamMode').attr("disabled", 'disabled').filter('[value=' + updateTeamMode + ']').attr("checked", 'checked')
				}
				if (userUID === teamOwner) {
					that.$teamInfoContainer.find('.j-dismissTeam').removeClass("hide")
					that.$teamInfoContainer.find('.j-exitTeam').addClass("hide")
				}else{
					if(applyUserAccid == userUID){
						that.$teamInfoContainer.find('.j-dismissTeam').addClass("hide")
						that.$teamInfoContainer.find('.j-exitTeam').addClass("hide")
					}
				}
				if (updateTeamMode === "all") {
					$teamName.addClass('owner')
					$teamDesc.addClass('owner')
					$teamAvatar.addClass('active')
				}
			} else {
				//讨论组
				that.$teamInfoContainer.addClass("normal").find('.j-exitTeam').text("退出讨论组")
				$teamName.addClass('owner')
				$teamDesc.addClass('owner')
				// $teamAvatar[0].src = "images/normal.png"
			}
		}
		$teamName.find('.name').text(teamName)
		$teramid.text(teamId)
		$createtime.text(transTimeFormatter(teamInfo.createTime))

		$teamDesc.find('.name').text(intro)
		// console.log("群组成员=",that.cache.getTeamMembers(teamId).members)
		var showMember = function () {
			members = that.cache.getTeamMembers(teamId).members
			// console.log("群成员==",that.cache.getTeamMembers(teamId))
			var array = []
			for (var i = 0; i < members.length; i++) {
				if (!that.cache.getUserById(members[i].account)) {
					array.push(members[i].account)
				}
			}
			if (array.length > 0) {
				getInfo(array)
			} else {
				showUI()
			}
		}
		var showUI = function () {
			showRole()
			that.sortTeamMembers(members)
			if (type === 'normal' || myTeamInfo.type !== "normal" || inviteMode === "all") { // 是群主
				html += '<li class="first add-item tc radius-circle" data-team-type="' + type + '" data-team-id="' + teamId + '"><i class="icon icon-plus"></i><p></p></li>'
			}
			for (var i = 0, l = members.length; i < l; ++i) {
				var member = members[i],
					account = member.account,
					avatar = getAvatar(that.cache.getUserById(account) ? that.cache.getUserById(account).avatar : ""),
					nick = getNick(account)
				html += '<li data-account="' + account + '"><a href="javascript:"><img src="' + avatar + '"/>'
				if (member.type === 'owner') {
					html += '<i class="icon radius-circle icon-user"></i>'
				} else {
					html += '<span class="hover" data-nick="' + nick + '" data-team-name="' + teamName + '" data-account="' + account + '" data-team-id="' + teamId + '">移除</span>'
				}
				html += '</a><p class="text">' + nick + '</p></li>'
			}
			$userList.html(html)
			if (myTeamInfo.type !== "normal") {
				$userList.addClass('owner')
			}
		}
		var getInfo = function (array) {
			that.mysdk.getUsers(array, function (err, data) {
				if (!err) {
					for (var j = 0; j < data.length; j++) {
						that.cache.updatePersonlist(data[j])
					}
					showUI()
				} else {
					layer.msg("获取用户信息失败",{icon:2})
				}
			})
		}
		that.getTeamMembers(teamId, showMember)
		that.$teamInfoContainer.removeClass('hide')
		that.getRelevanceCaseList(teamId)
		// /** 通话中的设置 */
		// var tmp = that.myNetcall;
		// tmp.$goNetcall.toggleClass("hide", !tmp.netcallActive);
	})
}

/********************************************************************
 * 关联案件
********************************************************************/
YX.fn.getRelevanceCaseList = function(teamId){
	var bodyInfo={
		"creditorName":"",
		"isRealte":"Y",
		"pageNum":"",
		"pageSize":"",
		"teamId":teamId
	}
	var that = this;
	firefly_IM_request.getRequest("get","/firefly-erp/teamRelationCases",bodyInfo,function(data){
		// console.log("关联案件列表=",data)
		if(data.isSuccess == "T"){
		  var relevanceList = data.body;
		  $("#relevanceNum").text(relevanceList.length);
		  //存储数据
		  that.relevanceCaseList = relevanceList;
		}else{
		  $("#relevanceNum").text(0)
		  layer.msg(data.errorMsg, {icon: 2});
		}
	},function(data){
		$("#relevanceNum").text(0)
	});
}

YX.fn.showRelevanceCase = function(){
	var that = this;
	this.$relevanceCaseContainer.removeClass('hide')
	this.$relevanceCaseContainer.load('./relevanceCase.html', function () {
		var relevanceCaseList = that.relevanceCaseList;
		var relevanceHtml = "";
		if(relevanceCaseList.length > 0){
			relevanceCaseList.forEach(function(item,index){
				relevanceHtml +=[
					'<div class="caseDetailInfo relevanceLi">',
						'<div class="caseIntroduction">',
							'<div class="fybgao">',
								'<div class="beigao"><img class="ybimg" src="images/bei.png" />'+(item.debtorName?item.debtorName:'暂无')+'</div>',
								'<div class="yangao"><img class="ybimg" src="images/yuan.png" />'+(item.creditorName?item.creditorName:'暂无')+'</div>',
								'</div>',
								'<div class="tip">'+item.statusDesc+'</div>'+
						'</div>',
						'<div class="statuslabel">',
							(item.caseBizMode?'<span>'+item.caseBizMode+'</span>':''),
						'</div>'+
						'<div class="amtdetails">',
							'<div class="caseli">',
							'<span class="spf">标的额</span>',
							'<span class="sps">'+(item.caseAmt/10000).toFixed(2)+'</span>',
							'<span class="spt">万元</span>',
							'</div>',
							'<div class="caseli">',
								'<span class="spf">申请人</span>',
								'<span class="spx">'+item.applyUserName+'</span>',
							'</div>',
							'<div class="caseli">',
								'<span class="spf">手机号</span>',
								'<span class="spx">'+formatePhone(item.mobileNo)+'</span>',
							'</div>',
							'<div class="caseli">',
								'<span class="spf">申请于</span>',
								'<span class="spx">'+item.applyDate+ " " +item.applyTime+'</span>',
							'</div>',
						'</div>',
					'</div>'
				].join("");
			});
			$(".relevanceCase").html(relevanceHtml)
		}else{
			$(".relevanceCase").html('<div>暂无关联案件列表</div>')
		}
		
            // $(".caseDetailInfo").html(introHtml)
			
	})
}

YX.fn.hiderelevanceCaseInfo = function(){
	this.$relevanceCaseContainer.addClass('hide')
	
}

YX.fn.sortTeamMembers = function (members) {
	if (!members || !members.length) return;
	members.sort(function (x, y) {
		if (x.type === "owner") {
			return -1
		} else if (y.type === "owner") {
			return 1
		} else if (x.type === "manager") {
			return -1
		} else if (y.type === "manager") {
			return 1
		} else {
			return 0
		}
	})
}
YX.fn.hideTeamInfo = function () {
	this.$teamInfoContainer.addClass('hide')
	this.$mask.addClass('hide')

	// /** 通话中的设置 */
	// var tmp = this.myNetcall;
	// tmp.$goNetcall.toggleClass("hide", true);
}

//移除群成员
YX.fn.removeTeamMember = function (event) {
	var ev = event || window.event,
		$target = $(ev.target),
		that = this,
		account = $target.attr('data-account'),
		teamId = $target.data('team-id'),
		teamType = $('#teamMemberList .first').data('team-type')
	this.mysdk.removeTeamMembers({
		teamId: teamId,
		accounts: [account],
		done: function (error, params) {
			if (error) {
				// alert('移除成员失败')
				layer.msg("移除成员失败", {icon: 2});
			} else {
				console.log("移除成功显示=",params)
				var teamId = that.crtSessionAccount;
				var members = that.cache.getTeamMembers(teamId).members.length -1
				that.$memberNum.text("( "+members+" )");
				$target.parents('li').remove()
			}

		}
	})
}

YX.fn.editTeamInfo = function () {
	var $this = $(this)
	if ($this.hasClass('owner')) {
		$this.parent('.wrap').addClass('active')
		$this.parent('.wrap').find("input").val($this.find('.name').text());
		$this.parent('.wrap').find("textarea").val($this.find('.name').text());
		$this.parent('.wrap').find("input").focus()
	}
}

YX.fn.saveTeamName = function () {
	var $input = $('#teamNameInput'),
		name = $input.val().trim(),
		that = this,
		teamId = this.crtSessionAccount
	if (name.length > 0) {
		// this.mysdk.updateTeam({
		// 	teamId: teamId,
		// 	name: name,
		// 	done: function (error, params) {
		// 		if (!error) {
		// 			var name = params.name
		// 			$('#teamName .name').text(name)
		// 			$input.val('').parents('.wrap').removeClass('active')
		// 		} else {
		// 			alert('群名称修改失败')
		// 		}
		// 	}
		// })
		//此处调用接口去更改
		//开始调用赢火虫内部服务的接口
		var bodyInfo = {
			"tid": teamId,
			"tname": name,
		  }
		  firefly_IM_request.getRequest("put","/netease-im/im/team",bodyInfo,function(data){
			  if(data.isSuccess == "T"){
				$('#teamName .name').text(name)
				$input.parents('.wrap').removeClass('active')
			  }else{
				// console.log("_that===",_that)
			  }
		  },function(data){
			layer.msg(data.errorMsg, {icon: 2});
		  });
	} else {
		$input.parents('.wrap').removeClass('active')
	}
}

YX.fn.hideTeamEditInfo = function(){
	var $input = $('#teamNameInput');
	$input.parents('.wrap').removeClass('active')
}

YX.fn.saveTeamDesc = function () {
	var $input = $('#teamDescInput'),
		name = $input.val().trim(),
		that = this,
		teamId = this.crtSessionAccount
	if (name.length > 0) {
		// this.mysdk.updateTeam({
		// 	teamId: teamId,
		// 	intro: name,
		// 	done: function (error, params) {
		// 		if (!error) {
		// 			var name = params.intro
		// 			$('#teamDesc .name').text(name)
		// 			$input.val('').parents('.wrap').removeClass('active')
		// 		} else {
		// 			alert('修改群介绍失败')
		// 		}
		// 	}
		// })
		//开始调用赢火虫内部服务的接口
		var bodyInfo = {
			"tid": teamId,
			"intro": name,
		  }
		  firefly_IM_request.getRequest("put","/netease-im/im/team",bodyInfo,function(data){
			  if(data.isSuccess == "T"){
				$('#teamDesc .name').text(name)
				$input.parents('.wrap').removeClass('active')
			  }else{
				layer.msg(data.errorMsg, {icon: 2});
			  }
		  },function(data){
	  
		  });
	} else {
		$input.parents('.wrap').removeClass('active')
	}
}
YX.fn.hideTeamIntEditInfo = function(){
	var $input = $('#teamDescInput');
	$input.parents('.wrap').removeClass('active')
}

YX.fn.setJoinMode = function (evt) {
	var joinMode = $(evt.target).val(),
		teamId = this.crtSessionAccount
	this.mysdk.updateTeam({
		teamId: teamId,
		joinMode: joinMode,
		done: function (error, params) {
			if (!error) {
			} else {
				layer.msg(error.message,{icon:2})
			}
		}
	})
}
YX.fn.setInviteMode = function (evt) {
	var inviteMode = $(evt.target).val(),
		teamId = this.crtSessionAccount
	this.mysdk.updateTeam({
		teamId: teamId,
		inviteMode: inviteMode,
		done: function (error, params) {
			if (!error) {
			} else {
				layer.msg(error.message,{icon:2})
			}
		}
	})
}
YX.fn.setBeInviteMode = function (evt) {
	var beInviteMode = $(evt.target).val(),
		teamId = this.crtSessionAccount
	this.mysdk.updateTeam({
		teamId: teamId,
		beInviteMode: beInviteMode,
		done: function (error, params) {
			if (!error) {
			} else {
				layer.msg(error.message,{icon:2})
			}
		}
	})
}
YX.fn.setUpdateTeamMode = function (evt) {
	var updateTeamMode = $(evt.target).val(),
		teamId = this.crtSessionAccount
	this.mysdk.updateTeam({
		teamId: teamId,
		updateTeamMode: updateTeamMode,
		done: function (error, params) {
			if (!error) {
			} else {
				layer.msg(error.message, {icon: 2});
			}
		}
	})
}
// 普通群（任何人）/高级群（非群主），退出群
YX.fn.exitTeam = function () {
	var that = this,
		teamId = this.crtSessionAccount;
	window.minAlert.alert({
		type: 'warnning',
		title:"确定要退出该群组么?",
		msg:"退出群组后将从列表中移除",
		cancelBtnMsg: '取消', //取消按钮的按钮内容
		confirmBtnMsg:'确定', //确定按钮的按钮内容
		showConfirm:true,
		cbConfirm: function(){
			that.mysdk.leaveTeam({
				teamId: teamId,
				done: function (error, params) {
					if (!error) {
						that.$teamInfoContainer.addClass('hide')
						that.$rightPanel.addClass('hide')
						// removeChatVernier(teamId)
						if($("#switchPanel a[data-type=sessions]").hasClass("cur")){
							$("#noSelectChat").removeClass("hide");
							return;
						}else if($("#switchPanel a[data-type=teams]").hasClass("cur")){
							$("#createNoTeamContainer").removeClass("hide");
							return;
						}
					} else {
						layer.msg(error.message, {icon: 2});
					}
				}
			})	
		}
	});
}
//高级群解散
YX.fn.doDismissTeam = function () {
	var that = this,
		teamId = this.crtSessionAccount
	// this.mysdk.dismissTeam({
	// 	teamId: teamId,
	// 	done: function (error, params) {
	// 		if (!error) {
	// 			that.$teamInfoContainer.addClass('hide')
	// 			that.$rightPanel.addClass('hide')
	// 			removeChatVernier(teamId)
	// 		} else {
	// 			alert(error.message)
	// 		}
	// 	}
	// });
	//调用接口进行解散群组
	window.minAlert.alert({
        type: 'warnning',
        title:"确定要解散该群组么?",
        msg:"解散后群组将从列表中移除",
        cancelBtnMsg: '取消', //取消按钮的按钮内容
        confirmBtnMsg:'确定', //确定按钮的按钮内容
        showConfirm:true,
        cbConfirm: function(){
			// var bodyInfo = {
			// 	"tid": teamId,
			//   }
			  firefly_IM_request.getRequest("delete","/netease-im/im/team?tid="+teamId,{},function(data){
				  if(data.isSuccess == "T"){
					that.$teamInfoContainer.addClass('hide')
					that.$rightPanel.addClass('hide')
					removeChatVernier(teamId)
					if($("#switchPanel a[data-type=sessions]").hasClass("cur")){
						$("#noSelectChat").removeClass("hide");
						return;
					}else if($("#switchPanel a[data-type=teams]").hasClass("cur")){
						$("#createNoTeamContainer").removeClass("hide");
						return;
					}
				  }else{
					// console.log("_that===",_that)
					layer.msg(data.errorMsg, {icon: 2});
				  }
			  },function(data){
		  
			  });
        }
      });
}
